﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Discuz.Toolkit;
using LY.Business.ServiceImpl;
using LY.Common;
using LY.Entity;
using LY.Interface;
using QJ.CMS.Controllers;
using LY.Extension;

namespace QJ.CMS.Filters
{
    //身份验证过滤器
    public class MyAuthorization : AuthorizeAttribute
    {
        /// <summary>
        /// 是否公司认证
        /// </summary>
        public string CompanyCertification { get; set; }
        //是否登陆验证
        public string IsLoginValidate { get; set; }

        public string ReturnUrl { get; set; }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Session["Token"] != null)
            {
                //分站凭证存在
                //filterContext.HttpContext.Response.Write("恭喜，分站凭证存在，您被授权访问该页面！");
            }
            else
            {
                //令牌验证结果
                if (filterContext.HttpContext.Request.QueryString["Token"] != null)
                {
                    if (filterContext.HttpContext.Request.QueryString["Token"] != "$Token$")
                    {
                        //持有令牌
                        string tokenValue = filterContext.HttpContext.Request.QueryString["Token"];
                        //调用WebService获取主站凭证 
                        var tokenService = new CBSSO.TokenServiceSoapClient();
                        var o = tokenService.TokenGetCredence2(tokenValue, LY.Common.Utils.Tools.GetIP());
                        if (o != null)
                        {
                            //令牌正确
                            filterContext.HttpContext.Session["Token"] = tokenValue;
                            var member = new U_Member
                                {
                                    IsCardValidate = o.IsCardValidate,
                                    IsIDValidate = o.IsIDValidate,
                                    IsEmailValidate = o.IsEmailValidate,
                                    IsBankValidate = o.IsBankValidate,
                                    IsPhoneValidate = o.IsPhoneValidate,
                                    IsPasswordValidate = o.IsPasswordValidate,
                                    QuestionOne = o.QuestionOne,
                                    AnswerOne = o.AnswerOne,
                                    SafeCode = o.SafeCode,
                                    RealName = o.RealName,
                                    Name = o.Name,
                                    Nickname = o.Nickname,
                                    Status = o.Status,
                                    InputTime = o.InputTime,
                                    Birthday = o.Birthday,
                                    LastLoginTime = o.LastLoginTime,
                                    MemberType = o.MemberType,
                                    AccountLocation = o.AccountLocation,
                                    Education = o.Education,
                                    Maritalstatus = o.Maritalstatus,
                                    Carcase = o.Carcase,
                                    Purchaseconditions = o.Purchaseconditions,
                                    Password = o.Password,
                                    Mobilenumber = o.Mobilenumber,
                                    Creditrating = o.Creditrating,
                                    DeptID = o.DeptID,
                                    CustomerID = o.CustomerID,
                                    CustomerService = o.CustomerService,
                                    IsIdentificate = o.IsIdentificate,
                                    HeadImage = o.HeadImage,
                                    RegistrationTime = o.RegistrationTime,
                                    QuestionTwo = o.QuestionTwo,
                                    AnserTwo = o.AnserTwo,
                                    Sex = o.Sex,
                                    QuestionThree = o.QuestionThree,
                                    AnserThree = o.AnserThree,
                                    IP = o.IP,
                                    Province = o.Province,
                                    City = o.City,
                                    MKey = o.MKey,
                                    Email = o.Email,
                                    SFTUserName = o.SFTUserName,
                                    SFTUserId = o.SFTUserId,
                                    YibaoId = o.YibaoId,
                                    Address = o.Address,
                                    Nationality = o.Nationality,
                                    EmergencyContactName = o.EmergencyContactName,
                                    EmergencyContactSex = o.EmergencyContactSex,
                                    EmergencyContactIDType = o.EmergencyContactIDType,
                                    EmergencyContactIDCode = o.EmergencyContactIDCode,
                                    EmergencyContactRelation = o.EmergencyContactRelation,
                                    EmergencyContactMobileNumber = o.EmergencyContactMobileNumber,
                                    EmergencyContactAddress = o.EmergencyContactAddress,
                                    EmergencyContactPostCode = o.EmergencyContactPostCode,
                                    ReceiveFileType = o.ReceiveFileType,
                                    PostCode = o.PostCode,
                                    MemberID = o.MemberID,
                                    ManagerID = o.ManagerID,
                                    RecommendCode = o.RecommendCode,
                                    ClientSource = o.ClientSource,
                                    Classify = o.Classify,
                                    Tel = o.Tel,
                                    IDType = o.IDType,
                                    IDCode = o.IDCode,
                                    ID = o.ID

                                };

                            HttpContext.Current.Session["CurrentUser"] = member;
                            //  filterContext.HttpContext.Response.Write("恭喜，令牌存在，您被授权访问该页面！");
                        }
                        else
                        {
                            //令牌错误
                            filterContext.HttpContext.Response.Redirect(this.replaceToken(filterContext));
                        }
                    }
                    else
                    {
                        //未持有令牌
                        filterContext.HttpContext.Response.Redirect(this.replaceToken(filterContext));
                    }
                }
                //未进行令牌验证，去主站验证
                else
                {
                    filterContext.HttpContext.Response.Redirect(this.getTokenURL(filterContext));
                }
            }

        }

        public void SetLogin(U_Member member)
        {
            // Utility.WriteCookie("DTRememberName", member.Name, 14400);
            // Utility.WriteCookie("AdminName", "DTcms", member.Name);
            //Utility.WriteCookie("AdminPwd", "DTcms", member.Password);
            // FormsAuthentication.SetAuthCookie(member.ID.ToString(), false);  

            if (ConfigurationManager.AppSettings["OpenBBS"].ToString() == "true")
            {
                //登陆论坛
                DiscuzSession ds = ConformityHandler.InitDiscuzSession();
                int DntUid = ds.GetUserID(member.Name);
                if (DntUid <= 0)
                {
                    DntUid = ds.Register(member.Name, member.Password, null, true);
                }
                ds.Login(DntUid, member.Password, true, 100, "");
            }

            //登陆日志;
            var memberLog = new U_MemberLoginLog
            {
                IP = RBSRequest.GetIP(),
                LoginTime = DateTime.Now,
                MemberID = member.ID,
                MemberName = member.Name,
                Status = 1,
                Remark = RBSRequest.GetIpCity()
            };

            IMemberLogService _memberLogService = new MemberLogService();
            _memberLogService.AddMemberLoginLog(memberLog);
        }

        //public override void OnAuthorization(AuthorizationContext filterContext)
        //{
        //    if (IsLoginValidate=="false")
        //    {
        //        return;
        //    }
        //    if (filterContext.RequestContext.HttpContext.Request.IsAuthenticated )
        //    {
        //        string adminname = Utility.GetCookie("AdminName", "DTcms");
        //        string adminpwd = Utility.GetCookie("AdminPwd", "DTcms");
        //        if (adminname != "" && adminpwd != "")
        //        {
        //            IMemberService iService = new MemberService();
        //            var member = iService.login(adminname, adminpwd);
        //            if (member != null)
        //            {
        //                HttpContext.Current.Session["CurrentUser"] = member;
        //            }
        //            else
        //            {
        //                FormsAuthentication.SignOut();
        //                IsLogin(filterContext);
        //            } 
        //            //if (!string.IsNullOrWhiteSpace(this.CompanyCertification))
        //            //{
        //            //    if (member.Classify != "企业")
        //            //    {
        //            //        this.CompanyCertification = "false";
        //            //    }
        //            //    else
        //            //    {
        //            //        this.CompanyCertification = "true";
        //            //           ICompanyService companyService=new CompanyService();
        //            //         var  company = companyService.GetCompany(member.ID);
        //            //        if (company.Status != 2)
        //            //        {
        //            //            this.CompanyCertification = "false";
        //            //        }
        //            //    } 
        //            //    if (this.CompanyCertification == "false")
        //            //    {

        //            //        filterContext.Controller.TempData.Add(RBSKeys.Error_Message, "发布项目需要认证企业，请进入用户中心进行认证！");
        //            //        filterContext.Result = new RedirectResult("/Default/Error");
        //            //    } 
        //            //}
        //        }
        //        else
        //        {
        //            FormsAuthentication.SignOut();
        //            IsLogin(filterContext);
        //        }
        //    }
        //    else
        //    {
        //        IsLogin(filterContext);
        //    } 
        //    //if (filterContext.RequestContext.HttpContext.Session != null && filterContext.RequestContext.HttpContext.Session["CurrentUser"] == null)
        //    //{
        //    //    string controlName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        //    //    string actionName = filterContext.ActionDescriptor.ActionName;
        //    //    var cookie = new HttpCookie("url", "/" + controlName + "/" + actionName);
        //    //    filterContext.HttpContext.Response.AppendCookie(cookie);
        //    //    filterContext.Result = new RedirectResult("/Login/Index");
        //    //}
        //}



        /// <summary>
        /// 获取带令牌请求的URL
        /// </summary>
        /// <returns></returns>
        private string getTokenURL(AuthorizationContext filterContext)
        {
            string url = filterContext.HttpContext.Request.Url.AbsoluteUri;

            if (!string.IsNullOrWhiteSpace(this.IsLoginValidate) && this.IsLoginValidate == "retrurnUrl")
            {
                url += "?retrurnUrl=" + filterContext.HttpContext.Request.UrlReferrer.AbsoluteUri;
            }

            Regex reg = new Regex(@"^.*\?.+=.+$");
            if (reg.IsMatch(url))
                url += "&Token=$Token$";
            else
                url += "?Token=$Token$";

            return ConfigurationManager.AppSettings["SsoUrl"] + "/sso/GetToken?BackURL=" + filterContext.HttpContext.Server.UrlEncode(url);
        }

        /// <summary>
        /// 去掉URL中的令牌
        /// </summary>
        /// <returns></returns>
        private string replaceToken(AuthorizationContext filterContext)
        {
            string url = filterContext.HttpContext.Request.Url.AbsoluteUri;
            if (!string.IsNullOrWhiteSpace(this.ReturnUrl))
            {
                url = this.ReturnUrl;
            }

            url = Regex.Replace(url, @"(\?|&)Token=.*", "", RegexOptions.IgnoreCase);
            return ConfigurationManager.AppSettings["SsoUrl"] + "/sso/userlogin?BackURL=" + filterContext.HttpContext.Server.UrlEncode(url);
        }

        public void IsLogin(AuthorizationContext filterContext)
        {
            string controlName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName = filterContext.ActionDescriptor.ActionName;
            string url = filterContext.HttpContext.Request.Url.ToString();
            url = filterContext.HttpContext.Server.UrlEncode(url);//给中文编码
            //var cookie = new HttpCookie("url", "/" + controlName + "/" + actionName);
            var cookie = new HttpCookie("url", url);
            filterContext.HttpContext.Response.AppendCookie(cookie);
            filterContext.Result = new RedirectResult(ConfigurationManager.AppSettings["SsoUrl"] + "?BackURL=" + url);
        }
    }
}